﻿// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
// 
// Copyright (c) Microsoft Corporation. All rights reserved.
// 
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------

namespace Microsoft.Samples.BabelCam.Phone.Pages
{
    using System;
    using System.Linq;
    using System.Windows;
    using System.Windows.Navigation;
    using Microsoft.Phone.Controls;
    using Microsoft.Phone.Shell;
    using Microsoft.Phone.Tasks;
    using Microsoft.Samples.BabelCam.Phone.Helpers;
    using Microsoft.Samples.BabelCam.Phone.Models;
    using Microsoft.Samples.BabelCam.Phone.ViewModel;

    public partial class UploadPhotoPage : PhoneApplicationPage
    {
        public UploadPhotoPage()
        {
            this.InitializeComponent();

            this.ViewModel = new UploadPhotoPageViewModel();

            this.languageFrom.ItemsSource = this.ViewModel.AvailableLanguages;
            this.languageFrom.SelectedItem = this.ViewModel.AvailableLanguages.FirstOrDefault(l => l.LanguageCode.Equals("en", StringComparison.OrdinalIgnoreCase));

            this.languageTo.ItemsSource = this.ViewModel.AvailableLanguages;
            this.languageTo.SelectedItem = this.ViewModel.AvailableLanguages.FirstOrDefault(l => l.LanguageCode.Equals("en", StringComparison.OrdinalIgnoreCase));
        }

        public UploadPhotoPageViewModel ViewModel
        {
            get { return this.DataContext as UploadPhotoPageViewModel; }
            set { this.DataContext = value; }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (this.ViewModel != null)
            {
                var useSampleImage = string.Empty;
                if (this.NavigationContext.QueryString.TryGetValue("useSampleImage", out useSampleImage))
                {
                    // Create an Uri to the sample text image to display it in the page.
                    var photoUri = new Uri("/Toolkit.Content/sampletext.jpg", UriKind.Relative);

                    // Get the stream of the sample text image from the application resources.
                    var photoStream = Application.GetResourceStream(new Uri("BabelCam.Phone;component/Resources/sampletext.jpg", UriKind.Relative)).Stream;

                    this.ViewModel.LoadPhoto(photoUri, photoStream);
                }
                else
                {
                    var photoResult = GetApplicationState<PhotoResult>("PhotoResult");
                    if (photoResult != null)
                    {
                        this.ViewModel.LoadPhoto(new Uri(photoResult.OriginalFileName), photoResult.ChosenPhoto);
                    }
                    else
                    {
                        this.NavigationService.GoBack();
                    }
                }
            }
        }

        private static T GetApplicationState<T>(string key)
        {
            if (!PhoneApplicationService.Current.State.ContainsKey(key))
            {
                return default(T);
            }

            return (T)PhoneApplicationService.Current.State[key];
        }

        private void OnUploadPicture(object sender, RoutedEventArgs e)
        {
            if (this.ViewModel != null)
            {
                var languageFrom = this.languageFrom.SelectedItem as LanguageChoice;
                var languageTo = this.languageTo.SelectedItem as LanguageChoice;

                var claimsUserNameIdentifier = App.CloudClientFactory.UserIdentifier;

                this.ViewModel.BlobName = string.Concat(Guid.NewGuid(), ".jpg");
                this.ViewModel.UserNameIdentifier = string.IsNullOrEmpty(claimsUserNameIdentifier) ? string.Empty : claimsUserNameIdentifier;
                this.ViewModel.FromLanguage = languageFrom.LanguageCode;
                this.ViewModel.ToLanguage = languageTo.LanguageCode;

                try
                {
                    this.ViewModel.UploadPhoto(
                        successMessage =>
                        {
                            this.Dispatcher.BeginInvoke(
                                () =>
                                {
                                    MessageBox.Show("Upload successful", "Upload Photo Result", MessageBoxButton.OK);
                                    PhoneApplicationService.Current.State.Remove("PhotoResult");
                                    this.NavigationService.GoBack();
                                });
                        },
                        errorMessage =>
                        {
                            this.Dispatcher.BeginInvoke(
                                () =>
                                {
                                    MessageBox.Show(errorMessage, "Upload Photo Result", MessageBoxButton.OK);
                                });
                        });
                }
                catch (Exception)
                {
                    this.NavigationService.GoBack();
                }
            }
        }
    }
}